package com.huiminpay.transaction.mq;


import com.alibaba.fastjson.JSON;
import com.huiminpay.paymentagent.api.conf.AliConfigParam;
import com.huiminpay.paymentagent.api.dto.AlipayTradeQueryDto;
import com.huiminpay.paymentagent.api.service.IAlipayAgentService;
import com.huiminpay.transaction.api.IPayChannelParamService;
import com.huiminpay.transaction.api.IPayOrderService;
import com.huiminpay.transaction.dto.OrderResultDTO;
import com.huiminpay.transaction.dto.PayChannelParamDTO;
import com.huiminpay.transaction.dto.PayOrderMqDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
@RocketMQMessageListener(topic = MqConst.PAY_ORDER_LISTENER,consumerGroup = "pay-producer-group")
@Slf4j
public class PayConsumer implements RocketMQListener<MessageExt> {


    @Reference
    IPayOrderService iPayOrderService;

    @Reference
    IPayChannelParamService iPayChannelParamService;

    @Reference
    IAlipayAgentService iAlipayAgentService;


    @Override
    public void onMessage(MessageExt messageExt) {
        log.info("收到消息{}" + LocalDateTime.now());

        //获取消息内容
        byte[] body = messageExt.getBody();


        String cnt = new String(body);
        //转化为PayOrderMqDto  获取订单ID
        PayOrderMqDto payOrderMqDto = JSON.parseObject(cnt, PayOrderMqDto.class);
        String outTradeNo = payOrderMqDto.getOutTradeNo();
        // 1. 查询自建系统订单信息
        //通过订单ID查询订单信息
        OrderResultDTO orderResultDTO = iPayOrderService.queryByOutTradeNo(outTradeNo);
        //如果状态是2或3代表订单已完成  直接返回
        if(orderResultDTO.getTradeState().equals("2")
                ||orderResultDTO.getTradeState().equals("3")){
            log.info("【当前订单已支付:{}】",cnt);
            return;
        }
        // 2. 判断支付类型
        //查询支付参数
        PayChannelParamDTO payChannelParamDTO =
                iPayChannelParamService.queryPayChannelParam(orderResultDTO.getAppId()
                        , orderResultDTO.getChannel()
                        , orderResultDTO.getPayChannel());
        String param = payChannelParamDTO.getParam();
        //获取支付类型
        String payChannel = payOrderMqDto.getPayChannel();
        if ("ALIPAY_WAP".equals(payChannel)){
            //如果是支付宝网页支付
            //解析参数 获取支付宝公共参数
            AliConfigParam aliConfigParam = JSON.parseObject(param, AliConfigParam.class);
            //调用代理服务，查询订单信息
            AlipayTradeQueryDto alipayTradeQueryDto = iAlipayAgentService.queryAlipayOrderByOutTradeNo(aliConfigParam, outTradeNo);
            //获取支付宝订单状态
            String tradeStatus = alipayTradeQueryDto.getTradeStatus();
            // WAIT_BUYER_PAY
            if(tradeStatus.equals("WAIT_BUYER_PAY")){
                // 订单未支付
                int reconsumeTimes = messageExt.getReconsumeTimes(); // 获取重试的次数
                if(reconsumeTimes>=8){
                    log.info("当前监听结束:{}",cnt);
                    //次数大于8此 ，不在重试
                    return;
                }
                throw new RuntimeException("消费重试！第"+reconsumeTimes+"次");
            }else {
                String tradeState = null;
                if(tradeStatus.equals("TRADE_CLOSED")){
                    //
                    tradeState = "4";
                }else if(tradeStatus.equals("TRADE_SUCCESS")){
                    tradeState = "2";
                }else if(tradeStatus.equals("TRADE_FINISHED")){
                    tradeState = "3";
                }
                //订单处于可更新状态
                orderResultDTO.setTradeState(tradeState);
                orderResultDTO.setPaySuccessTime(LocalDateTime.now());
                orderResultDTO.setTradeNo(alipayTradeQueryDto.getTradeNo());
                //更新订单状态
                iPayOrderService.updateTradeState(orderResultDTO);
            }

        }else if(payChannel.equals("WX_JSAPI")){
            // 使用微信api TODO


        }

    }
}
